package com.scisoft.scan.control.stock;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.scisoft.scan.control.CommonAdapter;
import com.scisoft.scan.control.CommonViewHolder;
import com.scisoft.scan.control.ScanHelper;
import com.scisoft.scan.data.BarCodeBean;
import com.scisoft.scan.data.stock.EasyPartBean;
import com.scisoft.scan.data.stock.PartSupplierBean;
import com.scisoft.scan.data.stock.StockInfoBean;
import com.scisoft.scan.dy.R;
import com.scisoft.scan.util.CommonUtil;
import com.scisoft.scan.ws.WebServiceHelper;
import com.scisoft.scan.ws.WebServiceHelper_Stock;
import com.squareup.picasso.Picasso;

import java.util.List;

public class EasyPartInfoActivity extends Activity {

    private ImageView iv_Back; //返回按钮
    private ImageView iv_jg;//价格
    private ImageView iv_kc;//库存
    private ImageView iv_img;
    private TextView tv_partNo;
    private TextView tv_partName;

    private EasyPartBean easyPartBean;

    private List<StockInfoBean> stockInfoBeanList;//配件的库存清单
    private List<PartSupplierBean> partSupplierBeanList;//供应商价格清单

    //列表
    PartInfoStockAdapter partInfoStockAdapter;
    PartSupplierPriceAdapter partSupplierPriceAdapter;
    private RecyclerView mRecyclerView;
    private LinearLayoutManager mLayoutManager;
    float lastY = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.activity_easy_part_info);
        //初始化扫码
        init();
        //参数传递
        Intent intent = getIntent();
        easyPartBean = (EasyPartBean)intent.getSerializableExtra("data");
        //返回
        iv_Back = findViewById(R.id.iv_back);
        iv_Back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //配件代码
        tv_partNo = findViewById(R.id.tv_partNo);
        tv_partNo.setText(easyPartBean.partCode);
        //配件名称
        tv_partName = findViewById(R.id.tv_partName);
        tv_partName.setText(easyPartBean.partName);
        //图片
        iv_img = findViewById(R.id.iv_img);
        if (easyPartBean.imgUrl != null && !easyPartBean.imgUrl.equals("")) {
            Picasso.with(EasyPartInfoActivity.this).load(easyPartBean.imgUrl).into(iv_img);
        } else {
            iv_img.setImageDrawable(getResources().getDrawable(R.drawable.ic_noimage));
        }
        iv_jg = findViewById(R.id.iv_jg);
        iv_jg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SetCurrentAdaper("0");
                QueryPartSupplierPrice();
            }
        });
        iv_kc= findViewById(R.id.iv_kc);
        iv_kc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SetCurrentAdaper("1");
                QueryPartStockInfo();
            }
        });

        //默认查询库存
        SetCurrentAdaper("1");
        QueryPartStockInfo();
    }

    //设置当前的列表 0 ：供应商价格  1：配件库存
    @SuppressLint("ClickableViewAccessibility")
    private void SetCurrentAdaper(String currentAdaper){
        //设置当前显示的列表信息（点击按钮时候切换）
        if(currentAdaper.equals("0")){
            //图标替换
            iv_jg.setImageResource(R.drawable.ic_jg2);
            iv_kc.setImageResource(R.drawable.ic_kc1);
            //供应商
            mRecyclerView = findViewById(R.id.lv_data);
            partSupplierPriceAdapter = new PartSupplierPriceAdapter(EasyPartInfoActivity.this);
            partSupplierPriceAdapter.setMultiPage(false);
            DisplayMetrics displayMetrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
            int fullWidth = displayMetrics.widthPixels;
            partSupplierPriceAdapter.setItemLayout(R.layout.item_partsupplierprice, R.id.hsv, R.id.layout_show, R.id.layout_hide, fullWidth);
            mLayoutManager = new LinearLayoutManager(this);
            mRecyclerView.setLayoutManager(mLayoutManager);
            mRecyclerView.setItemAnimator(new DefaultItemAnimator());
            //滚动的时候清空左滑按钮
            mRecyclerView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_UP:
                            if (Math.abs(event.getY() - lastY) > 5)
                                partInfoStockAdapter.clearLeftMenuList();
                    }
                    return false;
                }
            });
            mRecyclerView.setAdapter(partSupplierPriceAdapter);

        }else{
            iv_jg.setImageResource(R.drawable.ic_jg1);
            iv_kc.setImageResource(R.drawable.ic_kc2);
            //库存
            mRecyclerView = findViewById(R.id.lv_data);
            partInfoStockAdapter = new PartInfoStockAdapter(EasyPartInfoActivity.this);
            partInfoStockAdapter.setMultiPage(false);
            DisplayMetrics displayMetrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
            int fullWidth = displayMetrics.widthPixels;
            partInfoStockAdapter.setItemLayout(R.layout.item_partstock, R.id.hsv, R.id.layout_show, R.id.layout_hide, fullWidth);
            mLayoutManager = new LinearLayoutManager(this);
            mRecyclerView.setLayoutManager(mLayoutManager);
            mRecyclerView.setItemAnimator(new DefaultItemAnimator());
            //滚动的时候清空左滑按钮
            mRecyclerView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_UP:
                            if (Math.abs(event.getY() - lastY) > 5)
                                partInfoStockAdapter.clearLeftMenuList();
                    }
                    return false;
                }
            });
            mRecyclerView.setAdapter(partInfoStockAdapter);
        }
    }

    //region 库存查询部分
    //查询库存
    private void QueryPartStockInfo() {
        CommonUtil.showPress(this);
        QueryPartInfoStockTask queryPartInfoStockTask = new QueryPartInfoStockTask(EasyPartInfoActivity.this);
        queryPartInfoStockTask.execute();
    }

    //绑定数据
    private void BindStockData(Context context) {
        //配件代码
        if (stockInfoBeanList != null && stockInfoBeanList.size() > 0) {
            mRecyclerView.setVisibility(View.VISIBLE);
            //数据
            partInfoStockAdapter.clearLeftMenuList();
            partInfoStockAdapter.clearAddItem(stockInfoBeanList);
        } else {
            mRecyclerView.setVisibility(View.INVISIBLE);
        }
    }

    //查询配件库存信息服务
    class QueryPartInfoStockTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";

        QueryPartInfoStockTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                stockInfoBeanList = WebServiceHelper_Stock.STOCK_13(easyPartBean.partId);
                msg = "成功";
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                BindStockData(mcontext);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
                finish();
            }
        }
    }

    //适配器相关功能
    class PartInfoStockAdapter extends CommonAdapter<StockInfoBean> {

        //构造函数
        public PartInfoStockAdapter(Context context) {
            super(context);
        }

        @Override
        public void convert(CommonViewHolder holder, final StockInfoBean stockInfoBean, int position) {
            //获取相应索引的ItemBean对象
            final StockInfoBean bean = mList.get(position);
            //供应商
            TextView tv_supplierName =  holder.getView(R.id.tv_supplierName);
            //仓库名称
            TextView tv_depotName = holder.getView(R.id.tv_depotName);
            //库区
            TextView tv_areaName = holder.getView(R.id.tv_areaName);
            //货架
            TextView tv_positionName = holder.getView(R.id.tv_positionName);
            //库存
            TextView tv_count = holder.getView(R.id.tv_count);
            //占用
            TextView tv_usedcount = holder.getView(R.id.tv_usedcount);
            //可用
            TextView tv_canusecount = holder.getView(R.id.tv_canusecount);

            //设置控件的对应属性值
            tv_supplierName.setText(bean.supplierName);
            tv_depotName.setText(bean.depotName);
            tv_areaName.setText(bean.areaName);
            tv_positionName.setText(bean.position);
            tv_count.setText(String.valueOf(bean.stockCount));
            tv_canusecount.setText(String.valueOf(bean.canUseCount));
            tv_usedcount.setText(String.valueOf(bean.occupyCount));
        }
    }

    //endregion

    //region 价格查询部分
    //查询库存
    private void QueryPartSupplierPrice() {
        CommonUtil.showPress(this);
        QueryPartSupplierPriceTask queryPartSupplierPriceTask = new QueryPartSupplierPriceTask(EasyPartInfoActivity.this);
        queryPartSupplierPriceTask.execute();
    }

    //绑定数据
    private void BindSupplierPriceData(Context context) {

        if (partSupplierBeanList != null) {
            mRecyclerView.setVisibility(View.VISIBLE);
            //数据
            partSupplierPriceAdapter.clearLeftMenuList();
            partSupplierPriceAdapter.clearAddItem(partSupplierBeanList);
        } else {
            mRecyclerView.setVisibility(View.INVISIBLE);
        }
    }

    class QueryPartSupplierPriceTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";

        QueryPartSupplierPriceTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                partSupplierBeanList = WebServiceHelper_Stock.STOCK_14(easyPartBean.partId);
                msg = "成功";
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                BindSupplierPriceData(mcontext);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
                finish();
            }
        }
    }

    //适配器相关功能
    class PartSupplierPriceAdapter extends CommonAdapter<PartSupplierBean> {

        //构造函数
        public PartSupplierPriceAdapter(Context context) {
            super(context);
        }

        @Override
        public void convert(CommonViewHolder holder, final PartSupplierBean partSupplierBean, int position) {
            //获取相应索引的ItemBean对象
            final PartSupplierBean bean = mList.get(position);
            //供应商
            TextView tv_supplierName = holder.getView(R.id.tv_supplierName);
            //价格
            TextView tv_price = holder.getView(R.id.tv_price);

            //设置控件的对应属性值
            tv_supplierName.setText(bean.supplierName);
            tv_price.setText(String.valueOf(bean.price));
        }
    }

    //endregion

    //region 扫码相关
    //初始化
    private void init() {
        //初始化Profile
        ScanHelper.CreateProfile(this);
        //设置广播消息的接收器
        registerReceiver();
    }

    //查询条码服务
    class QueryBarCodeTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private String barCode;
        private BarCodeBean barCodeBean = null;

        QueryBarCodeTask(Context context, String barCode) {
            super();
            mcontext = context;
            this.barCode = barCode;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                barCodeBean = WebServiceHelper.ParseBarCode(barCode);
                msg = "成功";
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                //当前正在扫描配件
                if (barCodeBean == null || barCodeBean.barType == BarCodeBean.BAR_UNKNOWN) {
                    Toast.makeText(EasyPartInfoActivity.this, "无效二维码：" + barCode, Toast.LENGTH_LONG).show();
                } else if (barCodeBean.barType == BarCodeBean.BAR_SHELVES) {
                    Toast.makeText(EasyPartInfoActivity.this, "请扫描配件", Toast.LENGTH_LONG).show();
                } else {
                    //配置当前扫描的配件
                    //刷新当前配件的库存信息
                    SetCurrentAdaper("1");
                    QueryPartStockInfo();
                }
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //扫码处理
    private void ScanData(String barCode) throws Exception {
        if (barCode != null && barCode.length() > 0) {
            CommonUtil.showPress(this);
            QueryBarCodeTask queryBarCodeTask = new QueryBarCodeTask(EasyPartInfoActivity.this, barCode);
            queryBarCodeTask.execute();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        unRegisterReceiver();
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver();
    }

    //注册广播
    private void registerReceiver() {
        //IntentFilter intFilter = new IntentFilter(ScanManager.ACTION_SEND_SCAN_RESULT);
        //registerReceiver(mResultReceiver, intFilter);
        IntentFilter filter = new IntentFilter();
        filter.addAction(ScanHelper.ACTION_RESULT_NOTIFICATION);   // for notification result
        filter.addAction(ScanHelper.ACTION_RESULT);                // for error code result
        filter.addCategory(Intent.CATEGORY_DEFAULT);    // needed to get version info
        filter.addAction(ScanHelper.ACTION_SCAN_OUTPUT); // register to received broadcasts via DataWedge scanning
        registerReceiver(mResultReceiver, filter);
    }

    //取消注册广播
    private void unRegisterReceiver() {
        try {
            unregisterReceiver(mResultReceiver);
        } catch (Exception e) {
            Toast.makeText(this, "注销扫码失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    //监听扫码数据的广播，当设置广播输出时作用该方法获取扫码数据
    private BroadcastReceiver mResultReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ScanHelper.ACTION_SCAN_OUTPUT)) {
                // 处理扫码结果
                try {
                    String decodedData = intent.getStringExtra("com.symbol.datawedge.data_string");
                    ScanData(decodedData);
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(context, "扫描失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        }
    };

    //endregion
}
